/**
 * Copyright (C) 2012 Oleg Anastassov <o.anastasov@gmail.com>
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kz.kstu.ent.business.client.excel;

import kz.kstu.ent.business.common.exception.ExcelException;
import kz.kstu.ent.business.entity.Identifiable;
import kz.kstu.ent.util.DateUtil;
import kz.kstu.ent.util.NumberUtil;
import kz.kstu.ent.util.logger.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellReference;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author Oleg Anastassov
 */
public abstract class AbstractExcelImporter<T extends Identifiable> implements ExcelImporter<T> {

    private static final Logger LOGGER = Logger.getLogger(AbstractExcelImporter.class);

    public List<T> processImport(String file) throws ExcelException {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            Workbook workbook = new HSSFWorkbook(inputStream);
            return process(workbook);
        } catch (IOException e) {
            throw new ExcelException("Ошибка чтения файла", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
    }

    protected String getCellAddress(Cell cell) {
        CellReference cellRef = new CellReference(cell.getRow().getRowNum(), cell.getColumnIndex());
        return cellRef.formatAsString();
    }

    protected String getStringValue(Cell cell) throws ExcelException {
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                Double number = cell.getNumericCellValue();
                double decimal = number - number.intValue();
                if (decimal == 0) {
                    return String.valueOf(number.intValue());
                } else {
                    return NumberUtil.formatDouble(number);
                }
            case Cell.CELL_TYPE_STRING:
                return cell.getStringCellValue();
            case Cell.CELL_TYPE_BLANK:
                return null;
            default:
                throw new ExcelException("Illegal cell type");
        }
    }

    protected Date getDateValue(Cell cell) throws ExcelException {
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                return cell.getDateCellValue();
            case Cell.CELL_TYPE_STRING:
                SimpleDateFormat format = new SimpleDateFormat(DateUtil.SIMPLE_DATE_PATTERN);
                try {
                    return format.parse(cell.getStringCellValue());
                } catch (ParseException e) {
                    throw new ExcelException("Can not parse date");
                }
            case Cell.CELL_TYPE_BLANK:
                return null;
            default:
                throw new ExcelException("Illegal cell type");
        }
    }

    protected Double getDoubleValue(Cell cell) throws ExcelException {
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                return cell.getNumericCellValue();
            case Cell.CELL_TYPE_STRING:
                String str = cell.getStringCellValue();
                return Double.parseDouble(str);
            case Cell.CELL_TYPE_BLANK:
                return null;
            default:
                throw new ExcelException("Illegal cell type");
        }
    }

    protected Long getLongValue(Cell cell) throws ExcelException {
        Double number = getDoubleValue(cell);
        return number != null ? number.longValue() : null;
    }

    protected Integer getIntegerValue(Cell cell) throws ExcelException {
        Double number = getDoubleValue(cell);
        return number != null ? number.intValue() : null;
    }

    protected boolean isEmptyRow(Row row) {
        for (Cell cell : row) {
            if (cell.getCellType() != Cell.CELL_TYPE_BLANK) {
                return false;
            }
        }
        return true;
    }

    protected abstract List<T> process(Workbook workbook) throws ExcelException;
}
